package com.md.util.system;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.md.base.exception.ServerException;
import com.md.config.aliyun.sms.SmsClient;
import com.md.config.aliyun.sms.SmsConfig;
import com.md.value.enums.ErrorEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author 刘骄阳
 * 2023-08-08 15:25
 */
@Component
@RequiredArgsConstructor
public class AliYunUtils {
  private final SmsClient smsClient;

  public static SendSmsResponse sendSmsCode(final SmsConfig config,
                                            final String phone,
                                            final String content) {
    try {
      Client client = SmsClient.createClient(config.getAccessKeyId(), config.getAccessKeySecret(), config.getEndpoint(),
        config.getRegionId());
      SendSmsRequest sendSmsRequest = new SendSmsRequest()
        .setPhoneNumbers(phone)
        .setSignName(config.getSignName())
        .setTemplateCode(config.getTemplateCode())
        .setTemplateParam(content);
      return client.sendSms(sendSmsRequest);
    } catch (Exception e) {
      throw ServerException.build(ErrorEnum.SMS_SEND_ERROR, e);
    }
  }

  public SendSmsResponse sendSmsCode(final String phone, final String code) throws Exception {
    Client client = smsClient.createClient(null);
    SmsConfig smsConfig = smsClient.getSmsConfig(null);
    SendSmsRequest sendSmsRequest = new SendSmsRequest()
      .setPhoneNumbers(phone)
      .setSignName(smsConfig.getSignName())
      .setTemplateCode(smsConfig.getTemplateCode())
      .setTemplateParam("{\"code\":\"" + code + "\"}");
    return client.sendSms(sendSmsRequest);
  }
}
